'use strict';
// 引入uni-cloud的数据库模块
const db = uniCloud.database();

exports.main = async (event, context) => {
	const collection = db.collection('pjxx');
	try {
		// 获取数据
		const result = await collection.get();
		console.log('更新数据所有：',result);
		if(result.data){
			result.data.forEach(v => {
				let targetDate = new Date(v.dqr)
				// 计算距离目标日期的天数
				const now = new Date();
				// 将时间部分重置为午夜，避免时区问题
				const nowMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const targetMidnight = new Date(targetDate.getFullYear(), targetDate.getMonth(),targetDate.getDate());
				// 计算时间差（毫秒）
				const diff = targetMidnight - nowMidnight;
				// 转换为天
				let syts = Math.ceil(diff / (1000 * 60 * 60 * 24));
				let param = {
					syts: syts
				}
				console.log('更新',syts);
				//  更新数据
				collection.doc(v._id).update(param)
			})
		}
		return {
			success: true,
			message: '数据更新成功'
		};
	} catch (e) {
		console.error(e);
		return {
			success: false,
			message: '数据更新失败'
		};
	}
};